package top.hkyzf.study.datastructure.queue;

import java.util.Scanner;

/**
 * 数组模拟队列（环形队列）
 * @author 朱峰
 * @date 2020-12-18 9:34
 */
public class CircleQueue {
    private int head;
    private int tail;
    private int maxSize;
    private int [] array;

    public CircleQueue(int maxSize) {
        this.head = 0;
        this.tail = 0;
        this.maxSize = maxSize;
        this.array = new int[maxSize];
    }

    // 判断队列是否满（最后一个位置留空，所以maxSize=5时，四个数据就满了）
    public boolean isFull() {
        return (tail + 1)%maxSize == head;
    }

    // 队列是否为空
    public boolean isEmpty() {
        return head == tail;
    }

    public void addQueue(int i) {
        // 判断是否已满
        if(isFull()) {
            throw new RuntimeException("队列已满，无法添加");
        }
        array[tail] = i;
        tail = (tail+1)%maxSize;
    }

    public int getQueue() {
        // 判断是否是空的
        if(isEmpty()) {
            throw new RuntimeException("队列是空的，无法获取");
        }
        int temp = array[head];
        head = (head+1)%maxSize;
        return temp;
    }

    public void listQueue() {
        // 判断是否是空的
        if(isEmpty()) {
            throw new RuntimeException("队列是空的");
        }

        for(int i=head; i<head+size(); i++) {
            System.out.printf("a[%d]=%d\n", i-head, array[i%maxSize]);
        }
    }

    public int showHead() {
        // 判断是否是空的
        if(isEmpty()) {
            throw new RuntimeException("队列是空的，没有头元素");
        }
        return array[head];
    }

    public int size() {
        return (tail+maxSize-head)%maxSize;
    }
}
